#!/usr/bin/env python3
"""
OpenAI代理服务启动脚本
"""

import os
import sys
import uvicorn
from config import settings

def check_ssl_files():
    """检查SSL证书文件是否存在"""
    if not settings.enable_https:
        return True
    
    if not settings.ssl_certfile or not settings.ssl_keyfile:
        print("❌ 启用HTTPS需要配置ssl_certfile和ssl_keyfile")
        return False
    
    if not os.path.exists(settings.ssl_certfile):
        print(f"❌ SSL证书文件不存在: {settings.ssl_certfile}")
        return False
    
    if not os.path.exists(settings.ssl_keyfile):
        print(f"❌ SSL私钥文件不存在: {settings.ssl_keyfile}")
        return False
    
    if settings.ssl_ca_certs and not os.path.exists(settings.ssl_ca_certs):
        print(f"❌ CA证书文件不存在: {settings.ssl_ca_certs}")
        return False
    
    return True

def main():
    """启动代理服务"""
    print("🚀 启动 OpenAI Base URL 代理服务")
    
    # 检查HTTPS配置
    if not check_ssl_files():
        sys.exit(1)
    
    protocol = "https" if settings.enable_https else "http"
    print(f"📍 监听地址: {settings.proxy_host}:{settings.proxy_port}")
    print(f"🔒 协议: {protocol.upper()}")
    print(f"🔧 支持的后端: {list(settings.backends.keys())}")
    print(f"📝 日志级别: {settings.log_level}")
    print("-" * 50)
    
    # 显示认证信息
    print("🔐 认证方式: API密钥由调用方在请求头中提供")
    print("📋 支持的认证头:")
    for backend, config in settings.backends.items():
        auth_header = config.get("auth_header", "authorization")
        auth_prefix = config.get("auth_prefix", "Bearer ")
        example = f"{auth_prefix}sk-your-api-key" if auth_prefix else "your-api-key"
        print(f"   - {backend}: {auth_header}: {example}")
    
    print("-" * 50)
    print(f"🌐 服务地址: {protocol}://{settings.proxy_host}:{settings.proxy_port}")
    print(f"📊 管理界面: {protocol}://{settings.proxy_host}:{settings.proxy_port}/docs")
    print("-" * 50)
    print("📖 使用示例:")
    print(f'   curl -X POST "{protocol}://localhost:{settings.proxy_port}/openai/v1/chat/completions" \\')
    print('     -H "Authorization: Bearer sk-your-openai-key" \\')
    print('     -H "Content-Type: application/json" \\')
    print('     -d \'{"model": "gpt-3.5-turbo", "messages": [...]}\' ')
    print("-" * 50)
    
    if settings.enable_https:
        print("🔒 HTTPS配置:")
        print(f"   证书文件: {settings.ssl_certfile}")
        print(f"   私钥文件: {settings.ssl_keyfile}")
        if settings.ssl_ca_certs:
            print(f"   CA证书文件: {settings.ssl_ca_certs}")
        print("-" * 50)
    
    try:
        # 构建uvicorn配置
        uvicorn_config = {
            "app": "main:app",
            "host": settings.proxy_host,
            "port": settings.proxy_port,
            "reload": True,
            "log_level": settings.log_level.lower(),
            "access_log": True
        }
        
        # 如果启用HTTPS，添加SSL配置
        if settings.enable_https:
            uvicorn_config.update({
                "ssl_certfile": settings.ssl_certfile,
                "ssl_keyfile": settings.ssl_keyfile,
            })
            if settings.ssl_ca_certs:
                uvicorn_config["ssl_ca_certs"] = settings.ssl_ca_certs
        
        uvicorn.run(**uvicorn_config)
        
    except KeyboardInterrupt:
        print("\n👋 服务已停止")
    except Exception as e:
        print(f"\n❌ 启动失败: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main() 